#include "mainui.h"
#include "ui_mainui.h"
#include "QDebug"
#include <QImage>
#include "bmp.h"

#define TFT_WIDTH       320
#define TFT_HEIGHT      240

MainUI *MainUI::obj = NULL;

uint8 g_buffer[TFT_WIDTH * TFT_HEIGHT * 2];

void _update_end(UG_U8 *buffer, UG_U16 w, UG_U16 h)
{
    MainUI::obj->update_end(buffer, w, h);
}

/* Callback function for the info window */
void window_2_callback(UG_MESSAGE* msg)
{
   if ( msg->type == MSG_TYPE_OBJECT )
   {
      if ( msg->id == OBJ_TYPE_BUTTON )
      {
         switch( msg->sub_id )
         {
            case BTN_ID_0:
            {
               //UG_WindowHide( &window_2 );
               break;
            }
         }
      }
   }
}

UG_U8 *malloc_buffer_cb(UG_U32 size)
{
    qDebug("malloc buffer:%u", size);

    return (UG_U8 *)malloc(size);
}

MainUI::MainUI(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::MainUI)
{
	ui->setupUi(this);
	obj = this;
    connect(&update_timer, SIGNAL(timeout()), this, SLOT(update_gui()));

    UG_Init(&gui, malloc_buffer_cb);
    UG_DriverRegister(DRIVER_UPDATE_BUFFER, (void *)_update_end);

    UG_WindowCreate(&window_1, obj_buff_wnd_1, MAX_OBJECTS, window_2_callback);
    UG_WindowSetBackColor(&window_1, C_GREEN);
    UG_WindowResize(&window_1, 0, 0, 230, 180);

    UG_WindowCreate(&window_2, obj_buff_wnd_2, MAX_OBJECTS, window_2_callback);
    UG_WindowSetBackColor(&window_2, C_BLACK);
    UG_WindowResize(&window_2, 0, 0, 319, 239);

    UG_ButtonCreate(&window_1, &button_1, BTN_ID_0, 20, 20, 120, 80);
    UG_ButtonSetBackColor(&window_1, BTN_ID_0, C_BLUE);

    //UG_ButtonCreate(&window_2, &button_2, BTN_ID_0, 20, 20, 120, 80);
    //UG_ButtonSetBackColor(&window_2, BTN_ID_0, C_YELLOW);

    UG_ImageCreate(&window_2, &image_1, IMG_ID_0, 0, 0, 319, 239);
    UG_ImageSetBMP(&window_2, IMG_ID_0, &bmw);
    UG_ImageShow(&window_2, IMG_ID_0, 1);

    //UG_ConsoleSetArea(20, 20, 310, 80);
    //UG_ConsolePutString("hello world\n");

    //QImage image = QImage(g_buffer, TFT_WIDTH, TFT_HEIGHT, QImage::Format_RGB16);
    //ui->lcd->setPixmap(QPixmap::fromImage(image));

    //UG_ButtonShow(&window_1, BTN_ID_0);
    UG_ButtonShow(&window_2, BTN_ID_0);

    update_timer.start(50);
}

MainUI::~MainUI()
{
	delete ui;
}

void MainUI::on_btn_show_clicked()
{
    //UG_WindowShow(&window_1);
    UG_WindowShow(&window_2);
}


void MainUI::on_pushButton_2_clicked()
{
    //UG_WindowShow(&window_1);
    UG_SwitchPanel(1);
}

void MainUI::update_gui()
{
    UG_Update();
}

void MainUI::update_end(UG_U8 *buffer, UG_U16 w, UG_U16 h)
{
    qDebug("update end");

    QImage image = QImage(buffer, w, h, QImage::Format_RGB16);
    ui->lcd->setPixmap(QPixmap::fromImage(image));
}
